//
// Created by yyx on 7/24/24.
//

#ifndef CUDA_FRESHMAN_FRESHMAN_H
#define CUDA_FRESHMAN_FRESHMAN_H

#include <ctime>
#include <cstdio>
#include <sys/time.h>

void CHECK(cudaError_t call) {
    const cudaError_t error = call;
    if (error != cudaSuccess) {
        printf("ERROR: %s:%d", __FILE__, __LINE__);
        printf("code: %d, reason:%s\n", error, cudaGetErrorString(error));
        exit(1);
    }
}


void initData(float *ip, int size) {
    time_t t;
    srand((unsigned) time(&t));
    for (int i = 0; i < size; i++) {
        ip[i] = (float) (rand() & 0xffff) / 1000.0f;
    }
}

void initData_int(int *ip, int size) {
    time_t t;
    srand((unsigned) time(&t));
    for (int i = 0; i < size; i++) {
        ip[i] = (int) (rand() & 0xff) ;
    }
}



void checkResult(float *hostRef, float *gpuRef, const int N) {
    double epsilon = 1.0E-8;
    for (int i = 0; i < N; i++) {
        if (abs(hostRef[i] - gpuRef[i]) > epsilon) {
            printf("Results don\'t match!\n");
            printf("%f(hostRef[%d] )!= %f(gpuRef[%d])\n", hostRef[i], i, gpuRef[i], i);
            return;
        }
    }
    printf("Check result success!\n");
}

double cpuSecond() {
    struct timeval tp;
    gettimeofday(&tp, NULL); // 创建一个cpu计时器，返回从1970年1月1日0点以来到现在的秒数
    return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6);
}

void initDevice(int devId) {
    int dev = devId;
    cudaDeviceProp deviceProp;
    CHECK(cudaGetDeviceProperties(&deviceProp, dev));
    printf("Using device %d: %s\n", dev, deviceProp.name);
    CHECK(cudaSetDevice(dev));

}

void printMatrix(float *C, const int nx, const int ny) {
    float *ic = C;
    printf("Matrix<%d, %d>:\n", ny, nx);
    for (int i = 0; i < ny; i++) {
        for (int j = 0; j < nx; j++) {
            printf("%6f\t", ic[j]);
        }
        ic += nx;
        printf("\n");
    }
}

#endif //CUDA_FRESHMAN_FRESHMAN_H
